package com.wzm.api;


import com.wzm.utils.Utils;
import io.qameta.allure.restassured.AllureRestAssured;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import lombok.Data;
import lombok.NonNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;


@Data
public class ServiceAPI {


    private String baseUrl;
    private String basePath;
    private String port;
//    private static HashMap<String,String> map = new HashMap<>();
    private String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJmcm9tIjoid2ViIiwiZXhwIjoxNjg1Mzc2MjYxLCJ1c2VybmFtZSI6ImFkbWluIn0.QDpBGIRxxN4ihufua-q39upKo9CulnEBfCki5eb_GSc";
    protected final Logger logger = LoggerFactory.getLogger(this.getClass().getName());

    @NonNull
    public ServiceAPI(String host, String basePath){
        this.baseUrl = "http://" + host ;
        this.basePath = basePath;

//        isTokenExpired(number,passWord);
        if (this.baseUrl != null){
            RestAssured.baseURI = this.baseUrl;
            RestAssured.filters(new AllureRestAssured());
        }
    }

    public String getToken(String number, String passWord){
        Map<String,String> paramsMap = new HashMap<>();
        paramsMap.put("username",number);
        paramsMap.put("password",passWord);

        Response rsp = getSpecificGiven().log().all().
                body(paramsMap).
                when().
                post("/sys/login");
        rsp.then().log().all();
//        logger.info(rsp.getBody().asString());
        String token = Utils.extractToStr(rsp.getBody().asString(),"result.token");
        return token;
    }

    public void isTokenExpired(String number, String passWord){
        Response rsp = getSpecificGiven().log().all().
                when().
                get("/sys/getUserInfo");
        rsp.then().log().all();
        String message = Utils.extractToStr(rsp.getBody().asString(),"message");
//        int code = Utils.extractToInt(rsp.getBody().asString(),"code");
        if (message.equals("操作成功！")){
            return;
        }else {
            String token = getToken(number,passWord);
        }
    }

    public RequestSpecification getSpecificGiven() {
        RequestSpecification mGiven = RestAssured.given().baseUri(baseUrl);
//        if (port != 80 ) mGiven.port(port);
        mGiven.contentType("application/json;charset=utf-8");
        if (token != null) mGiven.header("X-Access-Token", token);
        return mGiven;
    }

}
